/**
 * @author Andrew Dzyuba
 *
 */

package com.webiatech.server.mail;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.webiatech.server.AplicationVariables;
import com.webiatech.server.exceptions.DontSendMail;





/**
 * @author basjka
 *
 */
public class MailAppEngine {
	
	/**
	 * @param address
	 * @param subject
	 * @param msgBody
	 */
	public void sendTXT(String address,String subject,String msgBody){
		
		//TODO: need recognizer address	
		
		try {
			sendTXT_L(parseMailAddress(address), subject, msgBody);
		} catch (DontSendMail e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * @param address
	 * @param subject
	 * @param msgBody
	 * @throws DontSendMail
	 */
	private void sendTXT_L(Map<String,String> address,String subject,String msgBody)throws DontSendMail{
				
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);		

		try {		
			
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(AplicationVariables.adminEmail[0],AplicationVariables.adminEmail[1]));
			
			//parse recipients address
			Set<String> mailList = address.keySet();			
			for (String  a : mailList){
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(a,address.get(a)));
			}			
			
			msg.setSubject(subject);
			
			
			msg.setText(msgBody);			
			Transport.send(msg);

		} catch (AddressException e) {			
			throw new DontSendMail();
		} catch (MessagingException e) {		
			throw new DontSendMail();
		} catch (Exception e){			
			throw new DontSendMail();
		}
	}
	
	/**
	 * @param address
	 * @param subject
	 * @param htmlBody
	 */
	public void sendHTML(String address,String subject,String htmlBody){
		
		//TODO: need recognizer address		
		
		try {
			sendHTML_L(parseMailAddress(address), subject, htmlBody);
		} catch (DontSendMail e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * @param ArrayList<EmailAddress>
	 * @param subject
	 * @param htmlBody
	 * */
	private void sendHTML_L(Map<String,String> address,String subject,String htmlBody)throws DontSendMail  {
		
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		
		try{
			Message msg = new MimeMessage(session);
			// just from apliction admin			
			msg.setFrom(new InternetAddress(AplicationVariables.adminEmail[0],AplicationVariables.adminEmail[1]));
			
			//parse recipients address
			Set<String> mailList = address.keySet();			
			for (String  a : mailList){
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(a,address.get(a)));
			}
			
			msg.setSubject(subject);
			
			
	        Multipart mp = new MimeMultipart();	
	        MimeBodyPart htmlPart = new MimeBodyPart();
	        htmlPart.setContent(htmlBody, "text/html");
	        mp.addBodyPart(htmlPart);      
	        
	        msg.setContent(mp);
	        Transport.send(msg);
	        
        
		} catch (AddressException e) {			
			throw new DontSendMail();
		} catch (MessagingException e) {		
			throw new DontSendMail();
		} catch (Exception e){			
			throw new DontSendMail();
		}
	}
	
	/* Metod for test
	public void sendMail() {
		String content = "Test Body";
		
		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+2"));
		String date = dateFormat.format(new Date());

		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("admin@webiatech.com"));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress("ad@webiatech.com"));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress("basjka@gmail.com"));
			message.setSubject("INTERNET");
			message.setText(MessageFormat.format("{0} - {1}", content, date));
			Transport.send(message);
		} catch (AddressException e) {
			//log.log(Level.SEVERE, "Error sending SMS", e);
		} catch (MessagingException e) {
			//log.log(Level.SEVERE, "Error sending SMS", e);
		} finally {
		}
	}*/
	
	
	
	
	/**
	 *  Old metod
	 * @param adress String by google fromat: Person Name <example@gmail.com>, .....
	 * @return 
	 */
	/*
	public static ArrayList<EmailAddress> parseMailRecipient(String adress){
		String [] addresP = adress.split(",");
		ArrayList<EmailAddress> addA = new ArrayList<EmailAddress>();
		
		for (String s:addresP){
			EmailAddress email = new EmailAddress();
			
			Pattern pattern = Pattern.compile("[a-zA-z\\d]+@[a-zA-z\\d]+\\u002E[a-z]{1,5}");
			Matcher matcher = pattern.matcher(s);
			if(matcher.find())email.email = matcher.group();
			
			Pattern pattern2 = Pattern.compile("\".+\"");
			Matcher matcher2 = pattern2.matcher(s);
			if(matcher2.find())email.name = matcher2.group();
			
			addA.add(email);
			
		}
		//TO-DO: 
		return addA;
	}*/
	
	/**
	 * @param adress Google format
	 * @return
	 */
	private Map<String, String> parseMailAddress(String adress){
		String [] addresP = adress.split(",");
		Map<String,String> adressSet = new HashMap<String, String>();
		
		for (String s:addresP){
			String mail = new String();
			String name = new String();
			
			Pattern pattern = Pattern.compile("[a-zA-z\\d]+@[a-zA-z\\d]+\\u002E[a-z]{1,5}");
			Matcher matcher = pattern.matcher(s);
			if(matcher.find())mail = matcher.group();
			
			Pattern pattern2 = Pattern.compile("\".+\"");
			Matcher matcher2 = pattern2.matcher(s);
			if(matcher2.find())name = matcher2.group();
			
			adressSet.put(mail, name.replaceAll("\"", ""));
			
		}		
		return adressSet;
	}

	public  void main(String args[]) {
		
		//Test parse addres
		

		/*Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		String msgBody = "Test";

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("admin@webiatech.com","webiatech.com Admin"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress("basjk@gmail.com", "Mr. User"));
			msg.setSubject("Your Example.com account has been activated");
			msg.setText(msgBody);
			Transport.send(msg);

		} catch (AddressException ea) {
			// ...
		} catch (MessagingException e) {
			// ...
		} catch (Exception e){
			//
		}*/
	}

}

/*
class EmailAddress{
	String name;
	String email;
}
*/